package com.mayspeed.jg.listener;

import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;

import com.mayspeed.jg.JingGong;
import com.mayspeed.jg.util.JGUtil;

/**
 * 监听类
 * @author May_Speed
 * @since 2017/4/22
 */
public class JGListener implements Listener {

	@EventHandler
	public void click(InventoryClickEvent e) {
		//判断是否为玩家
		if (!(e.getWhoClicked() instanceof Player)) {
			e.setCancelled(true);
			return;
		}
		//判断是否点击的是Gui
		if (e.getInventory().getTitle().equalsIgnoreCase(JingGong.getInstance().getConfig().getString("Gui.Title").replaceAll("&", "§"))) {
			//判断是否点击的是Gui之外
			if (e.getRawSlot() < 0) {
				e.setCancelled(true);
				return;
			}
			//取消事件
			e.setCancelled(true);
			Player player = (Player) e.getWhoClicked();
			if(e.getRawSlot() == 4) {
				if (JGUtil.getPlayerMoney(player) < JingGong.getInstance().getConfig().getDouble("Costs." + (JGUtil.getItemJingGongLevel(JGUtil.getItemInMainHand(player)) + 1))) {
					player.sendMessage(JingGong.getInstance().getMessage().getString("noHaveEnoughMoney").replaceAll("&", "§"));
					player.closeInventory();
					return;
				}
				JingGong.getInstance().jingGong(player);
			}
		}
	}
	
	/**
	 * 监听伤害事件
	 * @param e
	 */
	@SuppressWarnings("deprecation")
	@EventHandler
	public void damage(EntityDamageByEntityEvent e) {
		if ((e.getDamager() instanceof Player)) {
			Player player = (Player) e.getDamager();
			ItemStack is = JGUtil.getItemInMainHand(player);
			ItemMeta im = is.getItemMeta();
			if ((JingGong.getInstance().getConfig().getIntegerList("CanJgItem").contains(Integer.valueOf(is.getTypeId())))) {
				if (im.hasLore()) {
					double damage = e.getDamage();
					e.setDamage(damage + JingGong.getInstance().getConfig().getDouble("Damage." + JGUtil.getItemJingGongLevel(is)));
				}
			}
	    }
	}
}
